package com.dog.view.converter;

import com.dog.model.Region;
import com.dog.service.IRegionService;
import com.dog.spring.ServiceFactory;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

/**
 * User: Kuttubek Aidaraliev
 * Date: 04.05.2010
 * Time: 8:47:27
 */
public class RegionConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
        IRegionService regionService = ServiceFactory.getRegionService();
        Region region = null;
        try {
            region = regionService.get(new Long(s));
        } catch (Exception e){
            FacesMessage facesMessage = new FacesMessage("Conversation error occurred. ",
                    "Invalid Region selected. ");
            facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ConverterException(facesMessage);
        }
        if(region == null){
            FacesMessage facesMessage = new FacesMessage("Conversation error occurred. ",
                        "Region not found. ");
            facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ConverterException(facesMessage);
        }

        return region;

    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {

        if(o instanceof Region) {
            Region region = (Region)o;
            return region.getId().toString();
        }
        else throw new IllegalArgumentException("Argument must be Region object!");
    }

}
